import json
import os
import sys
from core.result_base import ResultBase
from common.logger import logger
from common.content_type import ContentType
from common.user_agent import useragent
from common.time_bdp import time_bdp
from api.field import field
import urllib3
urllib3.disable_warnings()

BASE_PATH = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
sys.path.append(BASE_PATH)


def field_url_preview(access_token,tb_id,field_ids,_t=time_bdp.time_stamp_13(),_xsrf=None):
    """
    提取字段的网址参数
    :param tb_id:工作表id
    :param field_ids:字段id,是一个列表
    :param _t:13位的时间戳
    :param _xsrf:
    :return: 自定义的关键字返回结果 result
    """
    result = ResultBase()
    payload = {
        "tb_id":tb_id,
        "field_ids":json.dumps(field_ids),
        "_t": _t,
        "_xsrf": _xsrf
    }

    headers = {
        "Content-Type": ContentType.MULTIPART_FORM_DATA.value,
        "User-Agent": useragent.get_user_agent_one()
    }

    cookies = {
        "access_token": access_token
    }

    res = field.url_preview(params=payload, headers=headers,cookies=cookies)
    result.success = False
    if res.json()["status"] == "0":
        result.success = True
    else:
        result.error = "接口返回码是 【 {} 】, 返回信息：{} ".format(res.json()["errstr"], res.json())
    result.payload = res.json()
    result.response = res
    logger.info("提取网址参数 ==>> 返回结果 ==>> {}".format(result.response.text))
    return result



def field_extract_preview(access_token,tb_id,field_id,_t=time_bdp.time_stamp_13(),_xsrf=None):
    """
    归并字段，提取预览
    :param tb_id:工作表id
    :param fields:字段id,是一个列表
    :param _t:13位的时间戳
    :param _xsrf:
    :return: 自定义的关键字返回结果 result
    """
    result = ResultBase()
    tmp_payload_1 = {
        "field_id":field_id
    }
    tmp_payload = {
        "fields":[tmp_payload_1],
        "title":"国家名称",
        "data_type":"string",
        "param":{}
    }


    payload = {
        "tb_id":tb_id,
        "fields":json.dumps([tmp_payload]),
        "_t": _t,
        "_xsrf": _xsrf
    }


    headers = {
        "Content-Type": ContentType.MULTIPART_FORM_DATA.value,
        "User-Agent": useragent.get_user_agent_one()
    }

    cookies = {
        "access_token": access_token
    }

    res = field.extract_preview(params=payload, headers=headers,cookies=cookies)
    result.success = False
    if res.json()["status"] == "0":
        result.success = True
    else:
        result.error = "接口返回码是 【 {} 】, 返回信息：{} ".format(res.json()["errstr"], res.json())
    result.payload = res.json()
    result.response = res
    logger.info("归并字段，提取预览 ==>> 返回结果 ==>> {}".format(result.response.text))
    return result




def field_merge(access_token,tb_id,field_id,_t=time_bdp.time_stamp_13(),_xsrf=None):
    """
    归并字段
    :param tb_id:工作表id
    :param field_ids:字段id,是一个列表
    :param _t:13位的时间戳
    :param _xsrf:
    :return: 自定义的关键字返回结果 result
    """
    result = ResultBase()

    tmp_payload_1 = {
        "field_id":field_id
    }
    tmp_payload = {
        "fields":[tmp_payload_1],
        "title":"国家名称"+time_bdp.time_stamp_13(),
        "data_type":"string",
        "ico_type":2,
        "param":{}
    }

    payload = {
        "tb_id":tb_id,
        "info":json.dumps([tmp_payload]),
        "_t": _t,
        "_xsrf": _xsrf
    }

    headers = {
        "Content-Type": ContentType.MULTIPART_FORM_DATA.value,
        "User-Agent": useragent.get_user_agent_one()
    }

    cookies = {
        "access_token": access_token
    }

    res = field.merge(params=payload, headers=headers,cookies=cookies)
    result.success = False
    if res.json()["status"] == "0":
        result.success = True
    else:
        result.error = "接口返回码是 【 {} 】, 返回信息：{} ".format(res.json()["errstr"], res.json())
    result.payload = res.json()
    result.response = res
    logger.info("归并字段 ==>> 返回结果 ==>> {}".format(result.response.text))
    return result



def field_get_length(access_token,tb_id,aggregator,data_type,flag="1",_t=time_bdp.time_stamp_13(),_xsrf=None):
    """
    获取长度
    :param tb_id:工作表id
    :param aggregator:计算字段函数表达式
    :param data_type:数据类型，文本，数值，日期
    :param flag:计算字段公式开放给该表被分配的人查看，1，否，是
    :param _t:13位的时间戳
    :param _xsrf:
    :return: 自定义的关键字返回结果 result
    """
    result = ResultBase()

    payload = {
        "tb_id":tb_id,
        "aggregator":aggregator,
        "data_type":data_type,
        "flag":flag,
        "_t":_t,
        "_xsrf":_xsrf
    }

    headers = {
        "Content-Type": ContentType.MULTIPART_FORM_DATA.value,
        "User-Agent": useragent.get_user_agent_one()
    }

    cookies = {
        "access_token": access_token
    }

    res = field.get_length(params=payload, headers=headers,cookies=cookies)
    result.success = False
    if res.json()["status"] == "0":
        result.success = True
    else:
        result.error = "接口返回码是 【 {} 】, 返回信息：{} ".format(res.json()["errstr"], res.json())
    result.payload = res.json()
    result.response = res
    logger.info("计算字段获取长度 ==>> 返回结果 ==>> {}".format(result.response.text))
    return result


def field_create(access_token,tb_id,aggregator,data_type,new_field_name,flag="1",original_field_name=None,is_display="0",fid=None,_t=time_bdp.time_stamp_13(),_xsrf=None):
    """
    新增计算字段
    :param tb_id:工作表id
    :param aggregator:计算字段函数表达式
    :param data_type:数据类型，文本，数值，日期
    :param flag:计算字段公式开放给该表被分配的人查看，1，否，是
    :param _t:13位的时间戳
    :param _xsrf:
    :return: 自定义的关键字返回结果 result
    """
    result = ResultBase()

    payload = {
        "tb_id":tb_id,
        "aggregator":aggregator,
        "data_type":data_type,
        "flag":flag,
        "new_field_name":new_field_name,
        "original_field_name":original_field_name,
        "is_display":is_display,
        "fid":fid,
        "_t":_t,
        "_xsrf":_xsrf
    }

    headers = {
        "Content-Type": ContentType.MULTIPART_FORM_DATA.value,
        "User-Agent": useragent.get_user_agent_one()
    }

    cookies = {
        "access_token": access_token
    }

    res = field.create(params=payload, headers=headers,cookies=cookies)
    result.success = False
    if res.json()["status"] == "0":
        result.success = True
    else:
        result.error = "接口返回码是 【 {} 】, 返回信息：{} ".format(res.json()["errstr"], res.json())
    result.payload = res.json()
    result.response = res
    logger.info("新增计算字段 ==>> 返回结果 ==>> {}".format(result.response.text))
    return result


def field_modify(access_token,tb_id,aggregator,data_type,original_field_name,new_field_name,fid,param=None,flag="1",is_display="0",_t=time_bdp.time_stamp_13(),_xsrf=None):
    """
    修改计算字段
    :param tb_id:工作表id
    :param aggregator:计算字段函数表达式
    :param data_type:数据类型，文本，数值，日期
    :param flag:计算字段公式开放给该表被分配的人查看，1，否，是
    :param _t:13位的时间戳
    :param _xsrf:
    :return: 自定义的关键字返回结果 result
    """
    result = ResultBase()

    payload = {
        "tb_id":tb_id,
        "aggregator":aggregator,
        "data_type":data_type,
        "flag":flag,
        "new_field_name":new_field_name,
        "original_field_name":original_field_name,
        "is_display":is_display,
        "fid":fid,
        "param":param,
        "_t":_t,
        "_xsrf":_xsrf
    }

    headers = {
        "Content-Type": ContentType.MULTIPART_FORM_DATA.value,
        "User-Agent": useragent.get_user_agent_one()
    }

    cookies = {
        "access_token": access_token
    }

    res = field.modify(params=payload, headers=headers,cookies=cookies)
    result.success = False
    if res.json()["status"] == "0":
        result.success = True
    else:
        result.error = "接口返回码是 【 {} 】, 返回信息：{} ".format(res.json()["errstr"], res.json())
    result.payload = res.json()
    result.response = res
    logger.info("修改计算字段 ==>> 返回结果 ==>> {}".format(result.response.text))
    return result


def field_dependency(access_token,tb_id,field_id,title,_t=time_bdp.time_stamp_13(),_xsrf=None):
    """
    检查字段是否存在依赖关系
    :param tb_id:工作表id
    :param field_id:字段id
    :param title:字段名称
    :param _t:13位的时间戳
    :param _xsrf:
    :return: 自定义的关键字返回结果 result
    """
    result = ResultBase()

    check_field_payload = {
        "field_id":field_id,
        "title":title,
    }
    payload = {
        "tb_id":tb_id,
        "check_field":json.dumps(check_field_payload),
        "_t":_t,
        "_xsrf":_xsrf
    }

    headers = {
        "Content-Type": ContentType.MULTIPART_FORM_DATA.value,
        "User-Agent": useragent.get_user_agent_one()
    }

    cookies = {
        "access_token": access_token
    }

    res = field.dependency(params=payload, headers=headers,cookies=cookies)
    result.success = False
    if res.json()["status"] == "0":
        result.success = True
    else:
        result.error = "接口返回码是 【 {} 】, 返回信息：{} ".format(res.json()["errstr"], res.json())
    result.payload = res.json()
    result.response = res
    logger.info("检查字段是否存在依赖关系 ==>> 返回结果 ==>> {}".format(result.response.text))
    return result


def field_delete(access_token,tb_id,fid,_t=time_bdp.time_stamp_13(),_xsrf=None):
    """
    删除字段
    :param tb_id:工作表id
    :param fid:字段id
    :param _t:13位的时间戳
    :param _xsrf:
    :return: 自定义的关键字返回结果 result
    """
    result = ResultBase()

    payload = {
        "tb_id":tb_id,
        "fid":fid,
        "_t":_t,
        "_xsrf":_xsrf
    }

    headers = {
        "Content-Type": ContentType.MULTIPART_FORM_DATA.value,
        "User-Agent": useragent.get_user_agent_one()
    }

    cookies = {
        "access_token": access_token
    }

    res = field.delete(params=payload, headers=headers,cookies=cookies)
    result.success = False
    if res.json()["status"] == "0":
        result.success = True
    else:
        result.error = "接口返回码是 【 {} 】, 返回信息：{} ".format(res.json()["errstr"], res.json())
    result.payload = res.json()
    result.response = res
    logger.info("删除计算字段 ==>> 返回结果 ==>> {}".format(result.response.text))
    return result

